<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores'
import { updateUserInfoAPI } from '@/api/user'

const userStore = useUserStore()

const avatarUrl = ref(userStore.avatarUrl || '/static/images/default.png')

const handleChooseAvatar = (e) => {
  // 获取临时文件路径（有效期约2小时）
  userStore.setAvatarUrl(e.detail.avatarUrl)
  avatarUrl.value = e.detail.avatarUrl
}

// 表单数据
const formModel = ref({
  nickname: '',
  gender: '',
  age: '',
  height: '',
  weight: '',
  userPrefers: [], // 口味偏好数组，直接存储中文字符串
})

// 所有可选口味（只需要中文名称）
const flavorOptions = [
  { name: '酸' },
  { name: '甜' },
  { name: '苦' },
  { name: '辣' },
  { name: '咸' },
  { name: '香' },
  { name: '麻' },
]

// 表单验证错误
const errors = ref({
  nickname: '',
  gender: '',
  age: '',
  height: '',
  weight: '',
})

// 计算BMI
const bmi = computed(() => {
  const height = parseFloat(formModel.value.height)
  const weight = parseFloat(formModel.value.weight)

  if (!height || !weight || height <= 0 || weight <= 0) {
    return ''
  }

  const heightInMeters = height / 100
  const bmiValue = weight / (heightInMeters * heightInMeters)
  return bmiValue.toFixed(1)
})

// BMI背景色
const bmiBgColor = computed(() => {
  const bmiValue = parseFloat(bmi.value)
  if (!bmiValue) return 'rgba(255, 255, 255, 0.95)'

  if (bmiValue < 18.5) {
    return 'rgba(64, 158, 255, 0.3)' // 偏瘦 - 蓝色
  } else if (bmiValue < 24) {
    return 'rgba(103, 194, 58, 0.3)' // 正常 - 绿色
  } else if (bmiValue < 28) {
    return 'rgba(230, 162, 60, 0.3)' // 偏重 - 橙色
  } else {
    return 'rgba(245, 108, 108, 0.3)' // 肥胖 - 红色
  }
})

// 性别选项
const genderOptions = [
  { label: '男', value: 'male' },
  { label: '女', value: 'female' },
]

// 验证函数
const validateNickname = (value) => {
  if (!value || !value.trim()) {
    return '请输入昵称'
  }
  if (value.length < 1 || value.length > 20) {
    return '昵称长度在1到20个字符'
  }
  return ''
}

const validateAge = (value) => {
  const age = parseInt(value)
  if (!value || isNaN(age) || age < 15 || age > 25) {
    return '请输入服务群体的年龄(15-25)'
  }
  return ''
}

const validateHeight = (value) => {
  const height = parseFloat(value)
  if (!value || isNaN(height) || height < 80 || height > 250) {
    return '请输入有效的身高(80-250cm)'
  }
  return ''
}

const validateWeight = (value) => {
  const weight = parseFloat(value)
  if (!value || isNaN(weight) || weight < 30 || weight > 500) {
    return '请输入有效的体重(30-500kg)'
  }
  return ''
}

// 验证表单
const validateForm = () => {
  let isValid = true

  errors.value.nickname = validateNickname(formModel.value.nickname)
  if (errors.value.nickname) isValid = false

  if (!formModel.value.gender) {
    errors.value.gender = '请选择性别'
    isValid = false
  } else {
    errors.value.gender = ''
  }

  errors.value.age = validateAge(formModel.value.age)
  if (errors.value.age) isValid = false

  errors.value.height = validateHeight(formModel.value.height)
  if (errors.value.height) isValid = false

  errors.value.weight = validateWeight(formModel.value.weight)
  if (errors.value.weight) isValid = false

  return isValid
}

// 切换口味偏好选择状态
const toggleFlavor = (flavorName) => {
  const index = formModel.value.userPrefers.indexOf(flavorName)
  if (index > -1) {
    // 移除已选择的口味
    formModel.value.userPrefers.splice(index, 1)
  } else {
    // 添加新选择的口味
    formModel.value.userPrefers.push(flavorName)
  }
}

// 检查口味是否已选择
const isFlavorSelected = (flavorName) => {
  return formModel.value.userPrefers.includes(flavorName)
}

// 保存信息
const saveProfile = async () => {
  if (!validateForm()) {
    const firstError = Object.values(errors.value).find((err) => err !== '')
    if (firstError) {
      uni.showToast({
        title: firstError,
        icon: 'none',
      })
    }
    return
  }

  try {
    uni.showLoading({ title: '保存中...' })

    // 构造类型正确的参数，包含中文口味偏好
    const updateData = {
      username: formModel.value.nickname,
      sex:
        formModel.value.gender === 'male'
          ? 1
          : formModel.value.gender === 'female'
          ? 0
          : undefined,
      age: formModel.value.age ? parseInt(formModel.value.age) : undefined,
      height: formModel.value.height
        ? parseInt(formModel.value.height)
        : undefined,
      weight: formModel.value.weight
        ? parseFloat(formModel.value.weight)
        : undefined,
      prefer: formModel.value.userPrefers,
    }

    await updateUserInfoAPI(updateData)
    userStore.avatarUrl = avatarUrl.value
    userStore.getUserInfo() //刷新用户信息

    uni.hideLoading()
    uni.showToast({
      title: '个人信息保存成功！',
      icon: 'success',
    })

    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none',
    })
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 初始化数据
onMounted(() => {
  if (userStore.userInfo) {
    formModel.value = {
      nickname: userStore.userInfo.username || '微信用户',
      gender:
        userStore.userInfo.sex === 1
          ? 'male'
          : userStore.userInfo.sex === 0
          ? 'female'
          : '',
      age: userStore.userInfo.age || '',
      height: userStore.userInfo.height || '',
      weight: userStore.userInfo.weight || '',
      userPrefers: userStore.userInfo.userPrefers || [], // 初始化中文口味偏好
    }
  }
})
</script>

<template>
  <view class="edit-profile-container">
    <!-- 页面头部 -->
    <view class="header-section">
      <view class="header-content">
        <view class="header-top">
          <text class="page-title">
            <text class="iconfont icon-tianxie"></text>
            编辑个人信息
          </text>
        </view>

        <!-- 用户头像 -->
        <view class="avatar-section">
          <view class="avatar-container">
            <button
              class="avatar-button"
              open-type="chooseAvatar"
              @chooseavatar="handleChooseAvatar"
            >
              <image :src="avatarUrl" class="avatar" mode="aspectFill" />
              <view class="avatar-overlay">
                <text class="iconfont icon-xiangji avatar-edit-icon"></text>
                <text class="avatar-edit-text">更换头像</text>
              </view>
            </button>
            <view class="avatar-ring"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-card">
        <view class="profile-form">
          <!-- 昵称 -->
          <view class="form-item">
            <text class="form-label">昵称</text>
            <uni-easyinput
              v-model="formModel.nickname"
              placeholder="请输入昵称"
              maxlength="20"
              :clearable="true"
              @blur="errors.nickname = validateNickname(formModel.nickname)"
            />
            <text class="error-text">{{ errors.nickname || '' }}</text>
          </view>

          <!-- 性别 -->
          <view class="form-item">
            <text class="form-label">性别</text>
            <view class="gender-selection">
              <view
                v-for="option in genderOptions"
                :key="option.value"
                class="gender-option"
                :class="{ active: formModel.gender === option.value }"
                @tap="
                  formModel.gender = option.value
                  errors.gender = ''
                "
              >
                <text
                  class="iconfont"
                  :class="option.value === 'male' ? 'icon-nan' : 'icon-nv'"
                ></text>
                <text class="gender-label">{{ option.label }}</text>
              </view>
            </view>
            <text class="error-text">{{ errors.gender || '' }}</text>
          </view>

          <!-- 年龄 -->
          <view class="form-item">
            <text class="form-label">年龄</text>
            <uni-easyinput
              v-model="formModel.age"
              type="number"
              placeholder="请输入年龄"
              :clearable="true"
              @blur="errors.age = validateAge(formModel.age)"
            >
              <template #right>
                <text class="input-unit">岁</text>
              </template>
            </uni-easyinput>
            <text class="error-text">{{ errors.age || '' }}</text>
          </view>

          <!-- 身高体重行 -->
          <view class="measurement-row">
            <view class="form-item half-width">
              <text class="form-label">身高</text>
              <uni-easyinput
                v-model="formModel.height"
                type="digit"
                placeholder="请输入身高"
                :clearable="true"
                @blur="errors.height = validateHeight(formModel.height)"
              >
                <template #right>
                  <text class="input-unit">cm</text>
                </template>
              </uni-easyinput>
              <text class="error-text">{{ errors.height || '' }}</text>
            </view>

            <view class="form-item half-width">
              <text class="form-label">体重</text>
              <uni-easyinput
                v-model="formModel.weight"
                type="digit"
                placeholder="请输入体重"
                :clearable="true"
                @blur="errors.weight = validateWeight(formModel.weight)"
              >
                <template #right>
                  <text class="input-unit">kg</text>
                </template>
              </uni-easyinput>
              <text class="error-text">{{ errors.weight || '' }}</text>
            </view>
          </view>

          <!-- 口味偏好 -->
          <view class="form-item">
            <text class="form-label">口味偏好</text>
            <view class="flavor-tags">
              <uni-tag
                v-for="flavor in flavorOptions"
                :key="flavor.name"
                :text="flavor.name"
                :type="isFlavorSelected(flavor.name) ? 'primary' : 'default'"
                :closable="isFlavorSelected(flavor.name)"
                @click="toggleFlavor(flavor.name)"
                @close="toggleFlavor(flavor.name)"
                class="flavor-tag"
              />
            </view>
            <text class="hint-text">选择您喜欢的口味，可多选</text>
          </view>

          <!-- BMI显示 -->
          <view class="bmi-section" v-if="bmi">
            <view class="bmi-card" :style="{ backgroundColor: bmiBgColor }">
              <text class="bmi-title">身体质量指数 (BMI)</text>
              <view class="bmi-value">
                <text class="bmi-number">{{ bmi }}</text>
              </view>
              <text class="bmi-formula">BMI = 体重(kg) ÷ 身高²(m)</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="action-buttons">
            <button class="cancel-btn" @tap="goBack">取消</button>
            <button class="save-btn" @tap="saveProfile">保存</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部说明 -->
    <view class="editinfo-footer">
      <text class="footer-text">您的数据仅用于更好地菜品推荐以及热量计算</text>
    </view>
  </view>
</template>

<style scoped lang="scss">
/* 样式保持不变 */
.edit-profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0 0 calc(40rpx + env(safe-area-inset-bottom)) 0;
}

/* 页面头部 */
.header-section {
  padding: 40rpx 32rpx;

  .header-content {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 40rpx;
    padding: 40rpx;
    box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    position: relative;
    overflow: hidden;

    .header-top {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 40rpx;

      .page-title {
        font-size: 40rpx;
        font-weight: 600;
        color: #333;
        display: flex;
        align-items: center;

        .iconfont {
          font-size: 44rpx;
          color: #667eea;
          margin-right: 16rpx;
        }
      }
    }

    .avatar-section {
      text-align: center;

      .avatar-container {
        position: relative;
        display: inline-block;
        margin-bottom: 16rpx;

        .avatar-button {
          position: relative;
          padding: 0;
          margin: 0;
          border: none;
          background: transparent;
          border-radius: 50%;
          overflow: hidden;

          &::after {
            border: none;
          }

          .avatar {
            width: 160rpx;
            height: 160rpx;
            border-radius: 50%;
            border: 6rpx solid rgba(102, 126, 234, 0.2);
            transition: all 0.3s ease;
            display: block;
          }

          .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
            border-radius: 50%;

            .avatar-edit-icon {
              font-size: 40rpx;
            }

            .avatar-edit-text {
              font-size: 20rpx;
              font-weight: 500;
            }
          }

          &:hover .avatar-overlay,
          &:active .avatar-overlay {
            opacity: 1;
          }
        }

        .avatar-ring {
          position: absolute;
          top: -6rpx;
          left: -6rpx;
          right: -6rpx;
          bottom: -6rpx;
          border: 4rpx solid transparent;
          border-radius: 50%;
          background: linear-gradient(45deg, #667eea, #764ba2);
          opacity: 0;
          animation: rotate 3s linear infinite;
          pointer-events: none;
        }

        &:active .avatar-ring {
          opacity: 0.6;
        }
      }
    }
  }
}

/* 表单区域 */
.form-section {
  padding: 0 32rpx;

  .form-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 40rpx;
    padding: 48rpx;
    box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid rgba(255, 255, 255, 0.2);

    .profile-form {
      .form-item {
        margin-bottom: 48rpx;

        .form-label {
          color: #333;
          font-weight: 600;
          font-size: 28rpx;
          margin-bottom: 16rpx;
          display: block;
        }

        .uni-easyinput {
          :deep(.uni-easyinput__content) {
            border-radius: 24rpx;
            border: 4rpx solid rgba(102, 126, 234, 0.1);
            transition: all 0.3s ease;
            box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
            background: rgba(255, 255, 255, 0.8);
            height: 88rpx;

            &.is-focused {
              border-color: #667eea;
              box-shadow: 0 0 0 8rpx rgba(102, 126, 234, 0.1);
            }
          }

          :deep(.uni-easyinput__content-input) {
            font-size: 32rpx;
            padding: 24rpx 32rpx;
            color: #333;

            &::placeholder {
              color: #999;
              font-size: 28rpx;
            }
          }
        }

        .input-unit {
          color: #666;
          font-size: 28rpx;
          margin-right: 16rpx;
        }

        .error-text {
          display: block;
          height: 24rpx;
          line-height: 24rpx;
          color: #ff6b6b;
          font-size: 24rpx;
          margin-top: 12rpx;
          margin-left: 8rpx;
          opacity: 1;
          transition: opacity 0.2s ease;

          &:empty {
            opacity: 0;
          }
        }

        // 口味偏好样式
        .flavor-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 16rpx;
          margin-bottom: 12rpx;
        }

        .flavor-tag {
          margin-bottom: 10rpx;
          cursor: pointer;
        }

        .hint-text {
          color: #999;
          font-size: 24rpx;
          margin-top: 8rpx;
          display: block;
        }
      }

      /* 性别选择 */
      .gender-selection {
        display: flex;
        gap: 32rpx;

        .gender-option {
          flex: 1;
          padding: 32rpx 24rpx;
          border: 4rpx solid rgba(102, 126, 234, 0.1);
          border-radius: 24rpx;
          text-align: center;
          transition: all 0.3s ease;
          background: rgba(255, 255, 255, 0.8);

          &:active {
            transform: scale(0.98);
          }

          &.active {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.1);

            .iconfont {
              color: #667eea;
            }

            .gender-label {
              color: #667eea;
              font-weight: 600;
            }
          }

          .iconfont {
            font-size: 48rpx;
            color: #999;
            margin-bottom: 16rpx;
            display: block;
            transition: color 0.3s ease;
          }

          .gender-label {
            font-size: 28rpx;
            color: #666;
            transition: all 0.3s ease;
          }
        }
      }

      /* 身高体重行 */
      .measurement-row {
        display: flex;
        gap: 32rpx;

        .half-width {
          flex: 1;
        }
      }

      /* BMI区域 */
      .bmi-section {
        margin: 24rpx 0;

        .bmi-card {
          border-radius: 32rpx;
          padding: 32rpx;
          color: #333;
          text-align: center;
          border: 2rpx solid rgba(255, 255, 255, 0.3);
          box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

          .bmi-title {
            font-size: 28rpx;
            opacity: 0.8;
            margin-bottom: 20rpx;
            display: block;
          }

          .bmi-value {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16rpx;

            .bmi-number {
              font-size: 56rpx;
              font-weight: bold;
            }
          }

          .bmi-formula {
            font-size: 24rpx;
            opacity: 0.7;
            display: block;
          }
        }
      }

      /* 操作按钮 */
      .action-buttons {
        display: flex;
        gap: 32rpx;
        margin-top: 64rpx;

        button {
          flex: 1;
          height: 96rpx;
          font-size: 32rpx;
          font-weight: 600;
          border-radius: 24rpx;
          transition: all 0.3s ease;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          text-align: center;

          &.cancel-btn {
            background: rgba(0, 0, 0, 0.05);
            color: #666;

            &:active {
              background: rgba(0, 0, 0, 0.1);
              transform: translateY(2rpx);
            }
          }

          &.save-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.4);

            &:active {
              transform: translateY(4rpx);
              box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
            }
          }
        }
      }
    }
  }
}

/* 动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 小程序适配 */
/* #ifdef MP-WEIXIN */
.avatar-section .avatar-container .avatar-button {
  .avatar-overlay {
    opacity: 0.8 !important; // 小程序中始终显示提示
    background: rgba(0, 0, 0, 0.3) !important;

    .avatar-edit-text {
      font-size: 18rpx !important;
    }
  }
}
/* #endif */

/* 底部说明 */
.editinfo-footer {
  text-align: center;

  .footer-text {
    margin-top: 32rpx;
    color: #666;
    font-size: 27rpx;
    opacity: 0.8;
    display: block;
    line-height: 1.5;
  }
}
</style>
